package com.im.service.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.im.service.common.Result;
import com.im.service.common.ServiceException;
import com.im.service.common.UploadResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * @author liuzhiqiang
 */
@RestController
@RequestMapping("/oss")
@CrossOrigin
@Slf4j
@Api(tags = {"oss 相关接口"})
public class OssController {

    @Autowired
    private OSSClient ossClient;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.rongHui}")
    private String rongHuiUrl;

    @ApiOperation(value = "上传")
    @PostMapping("/upload")
    public Result<UploadResult> upload(MultipartFile file) {
        try {
            // 文件夹命名
            String day = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
            String prefix = LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
            String filePath = new StringBuilder(day).append(StrPool.SLASH).append(prefix).append(StrPool.DASHED).append(file.getOriginalFilename()).toString();
            ossClient.putObject(bucketName, filePath, file.getInputStream());

            String point = endpoint.replaceAll("https://", "");
            String networkUrl = "https://" + bucketName + StrPool.DOT + point + StrPool.SLASH + filePath;
            log.info("网路地址: {}", networkUrl);
            UploadResult uploadResult = new UploadResult();

            networkUrl = rongHuiUrl + filePath;

            uploadResult.setUrl(networkUrl);
            uploadResult.setFileName(filePath);
            return Result.okData(uploadResult);
        } catch (Exception e) {
            log.error("Upload failed:", e);
            throw new ServiceException("上传失败");
        }
    }


    @ApiOperation(value = "文件访问")
    @GetMapping("/rongHui/{dir}/{fileName}.{type}")
    public ResponseEntity fileAccess(@PathVariable("dir") String dir, @PathVariable("fileName") String fileName, @PathVariable("type") String type) {
        try {
            String filePath = new StringBuilder(dir).append(StrPool.SLASH).append(fileName).append(StrPool.DOT).append(type).toString();
            OSSObject ossObject = ossClient.getObject(bucketName, filePath);
            byte[] bytes = IoUtil.readBytes(ossObject.getObjectContent());
            HttpHeaders headers = new HttpHeaders();
            ContentDisposition contentDisposition = ContentDisposition.builder("attchement").filename(fileName+StrPool.DOT+type, Charset.defaultCharset()).build();
            headers.setContentDisposition(contentDisposition);
            headers.setContentType(MediaType.parseMediaType(ossObject.getObjectMetadata().getContentType()));
            return new ResponseEntity(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("Upload failed:", e);
            throw new ServiceException("下载失败");
        }
    }
}
